﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace BDSimpleStatus.Models
{
    public class Authentication
    {
        private const string COOKIE_NAME = "BDSimpleStatus";
        private const string SALT_PRE = "E9@7&xv";
        private const string SALT_POST = "8$mqQ%x4";
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public bool isAuthenticated()
        {
            String hashPw = Sha256AString(SALT_PRE + Properties.Settings.Default.SuperUserPassword + SALT_POST);
            string shash = (string)HttpContext.Current.Session[COOKIE_NAME];
            //HttpCookie cookie = new HttpCookie(COOKIE_NAME);
            if (!string.IsNullOrEmpty(shash))
                return (hashPw == shash);

            HttpCookie cookie = HttpContext.Current.Request.Cookies[COOKIE_NAME];
            if (cookie != null)
                return (cookie.Value == hashPw);
            else
                return false;            
        }

        public bool Authenticate(string password)
        {
            String hashPw = Sha256AString(SALT_PRE + Properties.Settings.Default.SuperUserPassword + SALT_POST);
            String hashUsersPw = Sha256AString(SALT_PRE + password + SALT_POST);
            if (hashPw == hashUsersPw)
            {
                HttpCookie cookie = new HttpCookie(COOKIE_NAME);
                cookie.Value = hashPw;
                cookie.Expires = DateTime.Now.AddDays((double)14);
                HttpContext.Current.Response.Cookies.Add(cookie);
                HttpContext.Current.Session[COOKIE_NAME] = hashPw;
                return true;
            }
            else
                return false;
        }

        public static string Sha256AString(string s)
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
            SHA256Managed sha256 = new SHA256Managed();
            byte[] ByteHash = sha256.ComputeHash(buffer);
            StringBuilder sb = new StringBuilder(ByteHash.Length);
            for (int i = 0; i < ByteHash.Length; i++)
            {
                sb.Append(ByteHash[i].ToString("x2"));
            }
            logger.Debug("Sha256AString hash created: {0}", sb.ToString());
            return sb.ToString();
        }
    }

    
}